package com.xinting.piano.view;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.View;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by wuxinting on 15/10/31.
 * 一个基类，用于定时刷新画布的view
 */
public class PTimerView extends View {

    private Handler handler;
    private Runnable myRunnable;
    private long interval;
    private AtomicBoolean bStarted;

    /**
     * user's runnable
     */
    private Runnable runnable;

    public PTimerView(Context context) {
        super(context);
        initialize();
    }

    public PTimerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    private void initialize() {
        bStarted = new AtomicBoolean(false);

        handler = new Handler(Looper.myLooper());
        myRunnable = new Runnable() {
            @Override
            public void run() {
                if (runnable != null) {
                    runnable.run();
                }
                invalidate();
                synchronized (this) {
                    if (interval > 0) {
                        handler.postDelayed(this, interval);
                    }
                }
            }
        };
    }

    /**
     * 设置刷新间隔
     * @param interval 间隔的毫秒数
     */
    public synchronized void setInterval(long interval) {
        this.interval = interval;
    }

    public void setRunnable(Runnable runnable) {
        this.runnable = runnable;
    }

    /**
     * 开始定时刷新
     */
    public void start() {
        if (interval <= 0) return;
        if (isStarted()) return;

        handler.postDelayed(myRunnable, interval);
        bStarted.set(true);
    }

    public void stop() {
        if (!isStarted()) return;

        handler.removeCallbacks(myRunnable);
        bStarted.set(false);
    }

    public boolean isStarted() {
        return bStarted.get();
    }
}
